package com.touchfired.common.spring;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

/**
 * bean定位器
 *
 * @author 幸佳俊
 */
@Configuration
public class BeanLocator implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanLocator.applicationContext = applicationContext;
    }

    /**
     * 获取spring bean
     * @param tClass 指定bean类
     * @param <T> 指定bean类型
     * @return bean
     */
    public static <T> T getBean(Class<T> tClass) {
        if (applicationContext != null) {
            return applicationContext.getBean(tClass);
        }
        return null;
    }

    /**
     * 获取spring bean
     * @param beanName bean全包名
     * @return bean
     * @throws ClassNotFoundException bean全包名找不到时抛出
     */
    public static Object getBean(String beanName) throws ClassNotFoundException {
        if (StringUtils.isNotBlank(beanName)) {
            Class<?> aClass = Class.forName(beanName);
            return getBean(aClass);
        }
        return null;
    }

    /**
     * 根据类型获取bean的集合
     * @param tClass 类型class
     * @param <T> 指定类型
     * @return 类型集合
     */
    public static <T> Collection<T> getBeanOfType(Class<T> tClass) {
        return applicationContext.getBeansOfType(tClass).values();
    }
}
